package netWorkPrograming.test.test03;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.SocketException;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.locks.LockSupport;

/**
 * @author yangwenqi
 * @decs TODO
 * @date 2025/5/28
 */
public class ServerTasker implements Runnable{

    private Socket socket;
    private CopyOnWriteArrayList<Socket> clients;
    private Thread currentThread;

    public ServerTasker(Socket socket , CopyOnWriteArrayList<Socket> clients , Thread currentThread){
        this.socket = socket;
        this.clients = clients;
        this.currentThread = currentThread;
    }

    //读消息
    BufferedReader br;
    //写消息
    PrintWriter pw;

    //广播消息
    @Override
    public void run() {
        try {
            br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            String str = null;
            while ((str = br.readLine())!=null){
                if(str.equals("exit")){

                    for (Socket client : clients) {
                        if(client!=socket){
                            pw = new PrintWriter(client.getOutputStream());
                            pw.println(socket.getRemoteSocketAddress()+"已下线！");
                            pw.flush();
                        }
                    }
                    clients.remove(socket);
                    break;
                }else{

                    for (Socket client : clients) {
                        if(client!=socket){
                            pw = new PrintWriter(client.getOutputStream());
                            pw.println(socket.getRemoteSocketAddress()+"说："+str);
                            pw.flush();
                        }
                    }
                }
            }
        } catch (SocketException e) {
            System.out.println("客户端异常退出！");
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            LockSupport.unpark(currentThread);
            if(socket!=null){
                try {
                    socket.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }

    }
}
